import { api } from './auth';

export interface CreateDesignRequest {
  roomType: string;
  designStyle: string;
  prompt: string;
  file: File;
}

export interface Design {
  id: string;
  userId: number;
  roomType: string;
  designStyle: string;
  originalImageUrl: string;
  generatedImageUrl?: string;
  prompt: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  errorMessage?: string;
  creditsUsed: number;
  openaiRequestId?: string;
  isPublic?: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface DesignResponse {
  success: boolean;
  data: Design;
  message?: string;
}

export interface CreateDesignTaskResponse {
  success: boolean;
  data: {
    id: string;
    status: 'pending' | 'processing' | 'completed' | 'failed';
    creditsUsed: number;
  };
  message?: string;
}

export interface DesignListResponse {
  success: boolean;
  data: {
    designs: Design[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
  message?: string;
}

export interface DesignStatsResponse {
  success: boolean;
  data: {
    total: number;
    completed: number;
    processing: number;
    failed: number;
    pending: number;
  };
  message?: string;
}

export interface RoomTypesResponse {
  success: boolean;
  data: string[];
  message?: string;
}

export interface DesignStylesResponse {
  success: boolean;
  data: string[];
  message?: string;
}

// 创建设计
export const createDesign = async (request: CreateDesignRequest): Promise<CreateDesignTaskResponse> => {
  const formData = new FormData();
  formData.append('roomType', request.roomType);
  formData.append('designStyle', request.designStyle);
  formData.append('prompt', request.prompt);
  formData.append('image', request.file);

  const response = await api.post('/ai/designs', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  return response.data;
};

// 获取用户的所有设计
export const getUserDesigns = async (): Promise<DesignListResponse> => {
  const response = await api.get('/ai/designs');
  return response.data;
};

// 根据ID获取设计详情
export const getDesignById = async (id: string): Promise<DesignResponse> => {
  const response = await api.get(`/ai/designs/${id}`);
  return response.data;
};

// 删除设计
export const deleteDesign = async (id: string): Promise<{ success: boolean; message: string }> => {
  const response = await api.delete(`/ai/designs/${id}`);
  return response.data;
};

// 获取设计统计信息
export const getDesignStats = async (): Promise<DesignStatsResponse> => {
  const response = await api.get('/ai/designs/stats');
  return response.data;
};

// 获取可用的房间类型
export const getRoomTypes = async (): Promise<RoomTypesResponse> => {
  const response = await api.get('/ai/room-types');
  return response.data;
};

// 获取可用的设计风格
export const getDesignStyles = async (): Promise<DesignStylesResponse> => {
  const response = await api.get('/ai/design-styles');
  return response.data;
};

// 获取设计任务状态
export const getDesignStatus = async (id: string): Promise<DesignResponse> => {
  const response = await api.get(`/ai/designs/${id}`);
  return response.data;
};

// 更新设计公开状态
export const updateDesignPublicStatus = async (id: string, isPublic: boolean): Promise<DesignResponse> => {
  const response = await api.patch(`/ai/designs/${id}/public-status`, { isPublic });
  return response.data;
};

// 获取公开设计列表（无需认证）
export const getPublicDesigns = async (params?: {
  page?: number;
  limit?: number;
  roomType?: string;
  designStyle?: string;
}): Promise<DesignListResponse> => {
  const queryParams = new URLSearchParams();
  if (params?.page) queryParams.append('page', params.page.toString());
  if (params?.limit) queryParams.append('limit', params.limit.toString());
  if (params?.roomType) queryParams.append('roomType', params.roomType);
  if (params?.designStyle) queryParams.append('designStyle', params.designStyle);
  
  const response = await api.get(`/ai/designs/public?${queryParams.toString()}`);
  return response.data;
};

// 文生图设计请求接口
export interface TextToImageRequest {
  image: File;
  customPrompt: string;
  userId: string;
}

// 文生图设计
export const createTextToImageDesign = async (request: TextToImageRequest): Promise<DesignResponse> => {
  const formData = new FormData();
  formData.append('image', request.image);
  formData.append('customPrompt', request.customPrompt);
  formData.append('userId', request.userId);

  const response = await api.post('/ai/designs/text-to-image', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  return response.data;
};